package com.crm.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.crm.entity.Askers;
import com.crm.repository.AskersRepository;
import com.crm.service.AskersService;
import com.crm.util.FenyeUtil; 
/**
 * 次类为业务层 主要执行业务代码
 * 
 * @author hp
 *
 */
@Service
public class AskersServiceimpl implements AskersService{

	@Autowired
	private AskersRepository askersRepository;
	@Override
	/**
	 * 分页查询方法
	 */
	public FenyeUtil<Askers> FindAskerByPage(Askers ask, Integer page) {
		// TODO Auto-generated method stub
		Pageable pageable = PageRequest.of(page-1, 10);
		Page<Askers> pages = askersRepository.findAll(get(ask),pageable);
				FenyeUtil<Askers> fenye=new FenyeUtil<>();
		fenye.setData(pages.getContent());
		fenye.setCount((int)pages.getTotalElements());
		return fenye;
	}

	private Specification<Askers> get(Askers ask) {
		// TODO Auto-generated method stub
		return new Specification<Askers>() {
			
			@Override
			public Predicate toPredicate(Root<Askers> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				// TODO Auto-generated method stub
				Predicate predicate = criteriaBuilder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				if(!StringUtils.isEmpty(ask.getAskerName())) {
					expressions.add(criteriaBuilder.like(root.get("askerName"),"%"+ask.getAskerName()+"%"));
				}
				if(!StringUtils.isEmpty(ask.getCheckState())) {
					expressions.add(criteriaBuilder.equal(root.get("checkState"),ask.getCheckState()));
				}
				return predicate;
			}
		};
	}

	@Override
	public String DelAsk(Integer aid) {
		// TODO Auto-generated method stub
		try {
			askersRepository.deleteById(aid);
			return "操作成功";
		} catch (Exception e) {
			return "发生了错误请稍后再试";
			// TODO: handle exception
		}
	}

	@Override
	public String UpdAndSaveAsk(Askers ask) {
		try {
			Askers as=askersRepository.saveAndFlush(ask);
			System.out.println(as);
			return "操作成功";
		} catch (Exception e) {
			return "发生了错误请稍后再试";
			// TODO: handle exception
		}
	}

	@Override
	public List<Askers> GetQianDaoAll() {
		// TODO Auto-generated method stub
		return askersRepository.GetQianDaoAll();
	}

	@Override
	public List<Askers> findAllByAsker() {
		// TODO Auto-generated method stub
		return askersRepository.findAll();
	} 

}
